package com.tianyu.inspection.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tianyu.inspection.common.Constants;
import com.tianyu.inspection.common.enums.FileTypeEnum;
import com.tianyu.inspection.common.enums.RoState;
import com.tianyu.inspection.common.annotation.Permission;
import com.tianyu.inspection.common.component.AppConstants;
import com.tianyu.inspection.common.component.Validate;
import com.tianyu.inspection.entity.GeneralFacilities;
import com.tianyu.inspection.entity.User;
import com.tianyu.inspection.entity.model.OperateMo;
import com.tianyu.inspection.entity.model.QueryMo;
import com.tianyu.inspection.entity.vo.Point;
import com.tianyu.inspection.entity.vo.Ro;
import com.tianyu.inspection.entity.vo.ServiceRo;
import com.tianyu.inspection.service.api.IGeneralFacilitiesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**********************************
 * @Author YSW
 * @Description 阀室接口
 * @Date 2021/1/15 - 18:40
 **********************************/

@Slf4j
@RestController
@RequestMapping("/api/2.0/generalFacilities")
public class GeneralFacilitiesController {

    @Resource
    private IGeneralFacilitiesService generalFacilitiesService;

    @Resource
    private Validate validateModel;

    @Resource
    private ValueOperations<String, Object> valueOperations;

    @Resource
    private AppConstants appConstants;

    @GetMapping(value = "/list")
    @Permission(value = 4,tags = Constants.API_PATROL)
    public Ro<IPage<GeneralFacilities>> getPageList(HttpServletRequest request, @RequestHeader("u-projectId") Integer projectId,
                                                    @RequestHeader("u-uid") Integer userId){
        QueryMo queryMo = QueryMo.getQueryMo(request);
        Ro<IPage<GeneralFacilities>> ro = new Ro<>();
        int roleId = (int) request.getAttribute("roleId");
        if (roleId > 1){
            User loginUser = (User) valueOperations.get(appConstants.redisUserKey + userId);
            if (Objects.nonNull(loginUser)){
                final String generalFacilitiesTypeUse = loginUser.getGeneralFacilitiesTypeUse();
                try {
                    final Map<String, JSONArray> modelMap = new HashMap<>(1);
                    final JSONArray jsonArray = JSONArray.parseArray(generalFacilitiesTypeUse);
                    if (Objects.isNull(jsonArray) || jsonArray.size() == 0){
                        return ro.setResultEnum(RoState.FAIL).setMessage("类型未配置");
                    }else {
                        modelMap.put("general_facilities_type_id", jsonArray);
                    }
                    queryMo.setInMap(modelMap);
                }catch (Exception e){
                    log.error(e.getMessage());
                }
            }
        }
        queryMo.build(GeneralFacilities.class,projectId);
        return ro.setContent(generalFacilitiesService.searchListPage(queryMo));
    }

    @GetMapping(value = "/{id}")
    @Permission(value = 4,tags = Constants.API_PATROL)
    public Ro<GeneralFacilities> getOne(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<GeneralFacilities> ro = new Ro<>();
        if (Objects.isNull(id)){
            return ro.setResultEnum(RoState.PARAMS_MISS_ERROR);
        }
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(GeneralFacilities.class,projectId);
        GeneralFacilities generalFacilities = generalFacilitiesService.selectOne(queryMo);
        if (Objects.isNull(generalFacilities)){
            ro.setMessage("未查询到数据");
        }else {
            ro.setContent(generalFacilities);
        }
        return ro;
    }

    @PostMapping(value = "/load")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<List<Point>> load(@RequestBody JSONObject jsonObj, @RequestHeader("u-projectId") Integer projectId){
        Ro<List<Point>> ro = new Ro<>();
        if (Objects.isNull(jsonObj)){
            return ro.setResultEnum(RoState.FAIL).setMessage("参数错误");
        }else {
            final Boolean isMultiple = jsonObj.getBoolean("isMultiple");
            final Object data = jsonObj.get("data");
            final Object messageType = jsonObj.get("messageType");
            if (projectId == 1){
                projectId = jsonObj.getInteger("projectId");
            }
            final Integer pipelineId = jsonObj.getInteger("pipelineId");
            if (Objects.isNull(isMultiple) || Objects.isNull(data) || Objects.isNull(messageType) || Objects.isNull(projectId)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误");
            }else {
                if (validateModel.projectIdValidate(projectId)){
                    return ro.setResultEnum(RoState.FAIL).setMessage("项目ID错误");
                }
                if (Objects.nonNull(pipelineId) && validateModel.pipelineIdValidate(pipelineId,projectId)){
                    return ro.setResultEnum(RoState.FAIL).setMessage("管线ID错误");
                }
            }
        }
        if (!generalFacilitiesService.baseMsSaveByJson(jsonObj)) {
            return ro.setResultEnum(RoState.FAIL);
        }
        return ro;
    }

    @PostMapping(value = "/insert")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<GeneralFacilities> insert(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId){
        Ro<GeneralFacilities> ro = new Ro<>();
        operateMo.createBuild(GeneralFacilities.class,projectId);
        if (operateMo.getEntity().size() == 0){
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        String number = (String) operateMo.getEntity().get("number");
        String sceneImage = (String) operateMo.getEntity().get("sceneImage");
        Integer generalFacilitiesTypeId = (Integer) operateMo.getEntity().get("generalFacilitiesTypeId");
        Integer projectId1 = (Integer)operateMo.getEntity().get("projectId");
        Integer pipelineId = (Integer)operateMo.getEntity().get("pipelineId");
        if (Objects.isNull(projectId1)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[projectId]");
        } else {
            if (validateModel.projectIdValidate(projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[projectId],值不存在");
            }
        }
        if (Objects.nonNull(number)){
            final GeneralFacilities generalFacilities = validateModel.generalFacilitiesNumberValidate(number, projectId1);
            if (Objects.nonNull(generalFacilities)){
                if(generalFacilities.getState().equals(0)){
                    return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[number],值已存在");
                }else {
                    delete(generalFacilities.getId(),projectId1);
                }
            }
        }
        if (Objects.isNull(generalFacilitiesTypeId)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[generalFacilitiesTypeId]");
        } else {
            if (validateModel.generalFacilitiesIdValidate(generalFacilitiesTypeId)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[generalFacilitiesTypeId],值不存在");
            }
        }
        if (Objects.nonNull(pipelineId)){
            if (validateModel.pipelineIdValidate(pipelineId,projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
            }
        }
        if (Objects.nonNull(sceneImage)){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_VALUE_CHEST_IMG.getValue(),sceneImage)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[sceneImage],文件不存在或文件上传类别错误");
            }
        }
        if (!generalFacilitiesService.insert(operateMo)){
            ro.setResultEnum(RoState.FAIL);
        }
        return ro;
    }

    @PatchMapping(value = "/modify")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<GeneralFacilities> modify(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId){
        Ro<GeneralFacilities> ro = new Ro<>();
        final ServiceRo serviceRo = operateMo.updateBuild(GeneralFacilities.class, projectId);
        if (!serviceRo.getResult()){
            return ro.setResultEnum(RoState.FAIL).setMessage(serviceRo.getMessage());
        }
        if (operateMo.getEntity().size()==0){
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        if (Objects.isNull(operateMo.get("id"))){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少[id]字段,请传参后重试");
        }
        Integer id = (Integer) operateMo.get("id");
        String number = (String) operateMo.getEntity().get("number");
        String sceneImage = (String) operateMo.getEntity().get("sceneImage");
        Integer generalFacilitiesTypeId = (Integer) operateMo.getEntity().get("generalFacilitiesTypeId");
        Integer projectId1 = (Integer)operateMo.getEqMap().get("project_id");
        Integer pipelineId = (Integer)operateMo.getEntity().get("pipelineId");
        if (Objects.isNull(projectId1)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[projectId]");
        } else {
            if (validateModel.projectIdValidate(projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[projectId],值不存在");
            }
        }
        if (Objects.nonNull(number)) {
            final GeneralFacilities generalFacilities = validateModel.generalFacilitiesNumberValidate(number, projectId1);
            if (Objects.nonNull(generalFacilities) && (!generalFacilities.getId().equals(id))){
                if(generalFacilities.getState().equals(0)){
                    return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[number],值已存在");
                }else {
                    delete(generalFacilities.getId(),projectId1);
                }
            }
        }
        if (Objects.isNull(generalFacilitiesTypeId)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[generalFacilitiesTypeId]");
        } else {
            if (validateModel.generalFacilitiesIdValidate(generalFacilitiesTypeId)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[generalFacilitiesTypeId],值不存在");
            }
        }
        if (Objects.nonNull(pipelineId)) {
            if (validateModel.pipelineIdValidate(pipelineId,projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
            }
        }
        if (Objects.nonNull(sceneImage)){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_VALUE_CHEST_IMG.getValue(),sceneImage)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[sceneImage],文件不存在或文件上传类别错误");
            }
        }
        if (!generalFacilitiesService.update(operateMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("参数无匹配,修改失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/{id}")
    @Permission(value = 1,tags = Constants.API_SUPER)
    public Ro<GeneralFacilities> delete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<GeneralFacilities> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(GeneralFacilities.class,projectId);
        queryMo.getEqMap().remove("state");
        if (!generalFacilitiesService.delete(queryMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/logical/{id}")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<GeneralFacilities> logicallyDelete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<GeneralFacilities> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(GeneralFacilities.class,projectId);
        if (!generalFacilitiesService.logicallyDelete(queryMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }
}
